<template>
	<view>
		<cu-page-bg></cu-page-bg>
		<view class="cu-w-100">
			<cu-navbar title="分类设置" :placeholder="true" @leftClick="vk.navigateBack()" :showLeft="true" :leftIconColor="{color:backgroundStyle.color}" :titleStyle="{color:backgroundStyle.color}" :style="getBackgroundStyle"
				bgColor="rgb(255,255,255,0)"></cu-navbar>
			<view class="cu-w-100 cu-p-20 cu-border-box">
				<cu-card>
					<view class="cu-w-100 cu-row cu-font-weight cu-font-big cu-py-20">
						<view style="border-left: 10rpx solid #CCC; margin-right: 20rpx;"></view>
						分类设置
					</view>
					<view class="cu-w-100 cu-row cu-text-light-muted cu-font-weight cu-py-20">
						<view style="border-left: 6rpx solid #CCC; margin-right: 20rpx;"></view>内置类型
					</view>
					<view class="cu-w-100 cu-row cu-j-start cu-a-center">
						<block v-for="(item,idx) in typeDataList" :key="idx">
							<view v-if="(item.uid === 'admin' && item.isExtend === false)" class="cu-span24-6 cu-py-20" @click="selectType(item)">
								<view class="cu-w-100 cu-row cu-j-center cu-a-center">
									<cu-icon custom-prefix="iconfont" slot="icon" size="36" :name="item.icon"></cu-icon>
								</view>
								<view class="cu-w-100 cu-row cu-j-center cu-a-center cu-pt-10">{{item.name}}</view>
							</view>
						</block>
					</view>
					<view class="cu-w-100 cu-row cu-text-light-muted cu-font-weight cu-py-20">
						<view style="border-left: 6rpx solid #CCC; margin-right: 20rpx;"></view>自定义类型
					</view>
					<view class="cu-w-100 cu-row cu-text-light-muted cu-py-10">
						<view style="margin-left: 20px;">常按文字进行编辑</view>
					</view>
					<view class="cu-w-100 cu-row cu-j-start cu-a-center">
						<block v-for="(item,idx) in typeDataList" :key="idx">
							<view v-if="item.uid !== 'admin'" class="cu-span24-6 cu-py-20" @click="selectType(item)">
								<view class="cu-w-100 cu-row cu-j-center cu-a-center">
									<cu-icon custom-prefix="iconfont" slot="icon" size="36" :name="item.icon"></cu-icon>
								</view>
								<view class="cu-w-100 cu-row cu-j-center cu-a-center cu-pt-10"><u-tooltip @click="typeClick()" :showCopy="false" :text="item.name" :buttons="['编辑','删除']" bgColor="#e3e4e6"></u-tooltip></view>
							</view>
						</block>
						<view class="cu-span24-6 cu-py-20" @click="addTypeData()">
							<view class="cu-w-100 cu-row cu-j-center cu-a-center"><u-icon name="plus-circle" color="#2979ff" size="36"></u-icon></view>
							<view class="cu-w-100 cu-row cu-j-center cu-a-center cu-pt-10" style="color:#606266;font-size: 14px;">自定义类型</view>
						</view>
					</view>
				
				</cu-card>
			</view>
			
		</view>
		<u-popup :show="show" mode="left" @close="close" @open="open" :customStyle="{width:'120%'}">
			<view class="cu-w-100 cu-pt-50 cu-mt-50">
				<view class="cu-w-100 cu-row cu-text-light-muted cu-font-weight cu-p-20">
					<view style="border-left: 6rpx solid #CCC; margin-right: 20rpx;"></view>新增分类
				</view>
				<cu-card>
					<view>基本信息</view>
					<u--form labelPosition="left" labelWidth="auto" :labelStyle="{paddingRight:'20rpx'}"
						:model="typeData" ref="uForm">
						<u-form-item label="类型名称" prop="name" borderBottom>
							<u--input placeholder="请输入账本名称" v-model="typeData.name"
								border="none"></u--input>
						</u-form-item>
						<u-form-item label="图标" prop="icon" @click="pickerShow = true" borderBottom>
							<cu-picker :isIcon="true" iconSize="36" customPrefix="iconfont" @confirm="pickerConfirm()" @close="pickerShow = false" 
							@cancel="pickerShow = false" :show="pickerShow" v-model="typeData.icon"
							:columns="typeDataColumns" :defaultIndex="getDefaultIndex" :iconStyle="{marginLeft:'46%'}"></cu-picker>
							<view class="cu-w-100 cu-row cu-j-center cu-a-center">
								<cu-icon custom-prefix="iconfont" slot="icon" size="36" :name="selectIconName"></cu-icon>
							</view>
						</u-form-item>
						
					</u--form>
					<view class="cu-mt-20">
						<u-button :color="buttonColor" @click="submit">确认</u-button>
					</view>
				</cu-card>
			</view>
		</u-popup>
	</view>
</template>

<script>
	let vk = uni.vk;
	export default {
		computed: {
			getBackgroundStyle() {
				let style = {};
				style.background = "linear-gradient(45deg, " + this.main + ", " + this.secondary + ")";
				// 合并用户传递的背景色对象
				Object.assign(style, this.backgroundStyle);
				return style;
			},
			getDefaultIndex(){
				if (vk.myfn.isEmpty(this.typeDataColumns)) {
					return -1
				}
				return [this.typeDataColumns[0].indexOf(this.selectIconName)]
			}
		},
		data() {
			return {
				main: vk.getVuex('$app.color.main'),
				secondary: vk.getVuex('$app.color.secondary'),
				buttonColor: "linear-gradient(to right, " + vk.getVuex('$app.color.main') + "," + vk.getVuex('$app.color.secondary')+ ")",
				backgroundStyle: {
					color: "#FFF"
				},
				selectOptionIndex: undefined,
				enqrDataByPage: {},
				typeDataList:[],
				show: false,
				typeDataColumns: vk.getVuex('$typeData.typeDataColumns'),
				pickerShow:false,
				selectIconName:undefined,
				isInsert: true,
				typeData:{
					"name":"",
					"icon":""
				},
				rules: {
					'name': [{
						type: 'string',
						required: true,
						message: '请填写类型名称',
						trigger: ['blur', 'change']
					}, {
						type: 'string',
						required: true,
						max: 4,
						message: '类型名称不能超过4个字符',
						trigger: ['blur', 'change']
					}],
					'icon': {
						type: 'string',
						required: true,
						message: '请选择图标',
						trigger: ['blur', 'change']
					}
				},
			};
		},
		onLoad(options) {
			vk = uni.vk;
			this.$store.dispatch('$typeData/clearEnqrData');
			this.init(options);
		},
		onShow(){
			this.reloadData();
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		methods: {
			// 页面数据初始化函数
			init(options) {
				this.main = vk.getVuex('$app.color.main');
				this.secondary = vk.getVuex('$app.color.secondary');
			},
			selectType(data){
				const index = this.selectOptionIndex
				this.selectOptionIndex = undefined
				this.isInsert = false
				
				// 修改
				if (index === 0) {
					this.typeData = data
					this.typeData.oldName = data.name
					this.typeData.oldIcon = data.icon
					this.selectIconName = data.icon
					this.isInsert = false
					this.show = true
				}
				// 删除
				else if (index === 1) {
					this.delFun(data)
				}
			},
			typeClick(index){
				this.selectOptionIndex = index
			},
			reloadData(){
				console.log(111111111)
				// 获取已存在信息
				this.enqrDataByPage = vk.getVuex('$typeData.enqrDataByPage') || null;
				this.userRelationBook = this.enqrDataByPage.data
				// console.log("this.enqrDataByPage",this.enqrDataByPage)
				if (this.enqrDataByPage && (this.enqrDataByPage.data == null || this.enqrDataByPage.data.length == 0)) {
					// 查询账本信息
					this.enqrDataByPageFun()
				}
			},
			async enqrDataByPageFun() {
				let that = this
				const pagination = {
					"pageIndex": vk.getVuex('$typeData.enqrDataByPage.pagination.pageIndex') + 1,
					"pageSize": vk.getVuex('$typeData.enqrDataByPage.pagination.pageSize')
				}
				await vk.callFunction({
					url: 'client/typeData/kh/getTypeDataList',
					title: '请求中...',
					data: {
						need_user_info: true, // 注意，need_user_info是加在 data 的属性里，而不是与data同级
						pagination: pagination
					},
					success: async (res) => {
						await that.$store.dispatch('$typeData/enqrDataByPage', {res});
						that.enqrDataByPage = vk.getVuex('$typeData.enqrDataByPage') || null;
						that.typeDataList = that.enqrDataByPage.data || {}
						that.typeDataColumns= vk.getVuex('$typeData.typeDataColumns') || []
						
					},
					fail: (err) => {
						const msg = "查询失败-" + err.msg
						vk.alert(msg, "错误提示");
					}
				});
			},
			open() {},
			close() {
				this.show = false
			},
			addTypeData(){
				this.show = true
				this.isInsert = true
				this.typeData = {"name":"","icon":""}
				this.selectIconName = ""
			},
			pickerConfirm(e){
				this.pickerShow = false
				this.selectIconName = e.value[0] || undefined;
				this.typeData.icon = this.selectIconName
			},
			async submit() {
				if (vk.myfn.isEmpty(this.typeData.icon)) {
					vk.toast("请选择图标", "error");
					return
				}
				if (vk.myfn.isEmpty(this.typeData.name)) {
					vk.toast("请填写类型名称", "error");
					return
				}
				else if(this.typeData.name.length > 4) {
					vk.toast("不能超过4个字符", "error");
					return
				}
				// 执行注册
				if (this.isInsert) {
					this.insertFun()
				}
				// 执行修改
				else {
					this.updateFun()
				}
			},
			// 新增
			insertFun() {
				let that = this;
				vk.callFunction({
					url: 'client/typeData/kh/addTypeData',
					title: '请求中...',
					data: {
						need_user_info: true, // 注意，need_user_info是加在 data 的属性里，而不是与data同级
						typeData: that.typeData
					},
					success: (data) => {
						vk.toast("创建成功", "success");
						// 关闭刷新
						that.show = false
						that.typeData = {"name":"","icon":""}
						that.selectIconName = undefined
						that.$store.dispatch('$typeData/clearEnqrData');
						that.reloadData()
					},
					fail: (err) => {
						const msg = "创建失败-" + err.msg
						vk.alert(msg, "错误提示");
					}
				});
			},
			// 删除
			delFun(data){
				const that = this
				vk.confirm("删除后，如果存在该类型的数据，类型将全部修改为'其他'，请问是否删除", "提示", "确定", "取消", async (res) => {
				  if (res.confirm) {
				    // 点击确定按钮后的回调
				    await vk.callFunction({
				    	url: 'client/typeData/kh/delTypeDataById',
				    	title: '请求中...',
				    	data: {
				    		need_user_info: true, // 注意，need_user_info是加在 data 的属性里，而不是与data同级
				    		typeData: data
				    	},
				    	success: async (res) => {
				    		that.$store.dispatch('$typeData/clearEnqrData');
				    		that.reloadData()
				    	},
				    	fail: (err) => {
				    		const msg = "删除失败-" + err.msg
				    		vk.alert(msg, "错误提示");
				    	}
				    });
				  }
				});
			},
			// 修改
			updateFun() {
				let that = this;
				vk.callFunction({
					url: 'client/typeData/kh/updateTypeDataById',
					title: '请求中...',
					data: {
						need_user_info: true, // 注意，need_user_info是加在 data 的属性里，而不是与data同级
						typeData: that.typeData
					},
					success: (data) => {
						vk.toast("修改成功", "success");
						// 关闭刷新
						that.show = false
						that.typeData = {"name":"","icon":""}
						that.$store.dispatch('$typeData/clearEnqrData');
						that.reloadData()
					},
					fail: (err) => {
						const msg = "创建失败-" + err.msg
						vk.alert(msg, "错误提示");
					}
				});
			},
			
		}
	};
</script>

<style lang="scss" scoped>

</style>